<script>
export default {
  name: 'TestItem',
  data() {
    return {
      receive: {},
    }
  },
  methods: {
    doneEdit(event) {
      if (event.target.value.trim() === '') {
        alert('输入为空')
        return
      }
      this.$bus.$emit('editTodo', this.receive.id, event.target.value)
      this.receive.isEdit = false;
    },
    deleteTodo() {
      this.$bus.$emit('deleteTodo', this.receive.id)
    },
    startEdit(receive) {
      if (Object.prototype.hasOwnProperty.call(receive, 'isEdit')) {
        receive.isEdit = true;
      } else {
        this.$set(this.receive, 'isEdit', true);
      }
      // 聚焦到input元素上 nextTick 是异步的
      // 会在DOM更新后执行
      this.$nextTick(function () {
        this.$refs.inputLine.focus();
      });
    },
    changeStatus() {
      this.$bus.$emit('changeStatus', this.receive.id)
    },
  },
  props: {
    todo: Object,
  },
  mounted() {
    this.receive = this.todo;
  },

}

</script>

<template>
  <div class="test-item">
    <div class="checkbox">
      <input @change="changeStatus" type="checkbox" :checked="receive.done"/>
    </div>
    <div class="text">
      <input
          type="text"
          style="outline: none;width: 210px;height: 30px"
          @blur="doneEdit($event)"
          @keyup.enter="doneEdit($event)"
          v-if="receive.isEdit"
          ref="inputLine"
          v-model="receive.text"/>
      <span v-else>{{ receive.text }}</span>
      <button style="float: right;margin-right: 10px;color: white;background: rgba(157,9,9,0.73)"
              @click="deleteTodo(receive.id)">删除
      </button>
      <button style="float: right;margin-right: 10px;color: white;background: green" @click="startEdit(receive)">编辑
      </button>
    </div>
  </div>
</template>

<style scoped>


.test-item {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 50px;
  border: 1px #ccc solid;
}

.text {
  text-align: left;
  width: 95%;
  float: right;
}

.checkbox {
  float: left;
  width: 5%;
}

</style>